package com.ck.core.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
import java.util.Map;

/**
 * JJWT加密、解析
 *
 * @author dxy
 * @date 2018/11/15 10:55
 */
public class JWTUtils {

	private static final String SECRET = "(EE-C_eCw7mLgmEp08345734p6nUSeCB9!@#$%^&*oB9KMA7ceyJ1c2VyTmF#%^$%!#@$tZSI6InN1cGVyYWRtaW4iLCJleHAiO&%$^&%^&j$#%#$%E1NDIyNzEzOTd94qzPgioapq1sB2qyXtfom8ih43h89jekMdUnn9zQ_A8QEuZ3k0cAeyJhbG?><MNBVCXciOiJIUzUxMiJ9";
	private static final String USER_NAME = "username";
	private static final Long DEFAULT_EXPIRE_TIME = 24 * 60 * 60 * 1000L;

	public static String generateJWTToken(Map<String,String> dataMap) {
		return generateJWTToken(DEFAULT_EXPIRE_TIME,dataMap);
	}
	
	/**
	 * 生成JJWTToken
	 *
	 * @param ttlMillis 超时时间（毫秒）
	 * @param dataMap  数据集合
	 * @return String
	 */
	public static String generateJWTToken(long ttlMillis, Map<String,String> dataMap) {
		//当前日期
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		try {
			Algorithm algorithm = Algorithm.HMAC256(SECRET);
			JWTCreator.Builder builder = JWT.create();
			builder.withIssuedAt(now);

			// 数据集，用于解析时反向获取数据
			if (  dataMap != null && !dataMap.isEmpty() ) {
				for (Map.Entry<String, String> entry : dataMap.entrySet()) {
					builder.withClaim(entry.getKey(), entry.getValue());
				}
			}

			//超时设置
			if (ttlMillis >= 0) {
				long expMillis = nowMillis + ttlMillis;
				Date exp = new Date(expMillis);
				builder.withExpiresAt(exp);
			}
			return builder.sign(algorithm);
		} catch (JWTCreationException exception) {
			throw exception;
		}
	}


	/**
	 * 解析JWTToken
	 *
	 * @param token 加密的JWTToken
	 * @return Claims
	 */
	public static Map<String, Claim> parseJWTToken(String token) {
		try {
			Algorithm algorithm = Algorithm.HMAC256(SECRET);
			JWTVerifier verifier = JWT.require(algorithm).build();
			//Reusable verifier instance
			DecodedJWT jwt = verifier.verify(token);
			return jwt.getClaims();
		} catch (JWTVerificationException exception){
			throw exception;
		}
	}

	/**
	 * 获取claim
	 *
	 * @param token 加密的JWTToken
	 * @return Claims
	 */
	public static Claim getClaimByKey(String token,String key) {
		try {
			Map<String, Claim> stringClaimMap = parseJWTToken(token);
			if ( stringClaimMap != null ) {
				return stringClaimMap.get(key);
			}
		} catch (JWTVerificationException exception){
			throw exception;
		}
		return null;
	}

}
